﻿using Enterprise_Get.API.Infrastructures.Interfaces;
using MediatR;
using MySqlX.XDevAPI.Common;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using System.Linq;
using THE_WIND_RISES.Common.Domans.BasicInformation.Departments;

namespace Enterprise_Get.API.Application.Commands.BasicInformations
{
    public class EnterpriseQueryHandler : IRequestHandler<EnterpriseQueryCommand, THE_WIND_RISES.Common.Dtos.Result>
    {

        /// <summary>
        /// 企业仓储
        /// </summary>
        private readonly IBaseRepositoryGet<Enterprise> enterpriseRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="enterpriseRepository"></param>
        public EnterpriseQueryHandler(IBaseRepositoryGet<Enterprise> enterpriseRepository)
        {
            this.enterpriseRepository = enterpriseRepository;
        }

        public async Task<THE_WIND_RISES.Common.Dtos.Result> Handle(EnterpriseQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new THE_WIND_RISES.Common.Dtos.Result() { Code = (int)CommonErrorCodes.Search };

            try
            {
                var sql = "select * from Enterprise";
                var list = enterpriseRepository.GetAll(sql);

                if (!string.IsNullOrEmpty(request.EnterpriseName))
                {
                    list = list.Where(x => x.EnterpriseName.Contains(request.EnterpriseName)).ToList();
                }

                var totalCount = list.Count();

                var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);

                list = list.OrderBy(x => x.EnterpriseId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

                var aa = new
                {
                    list,
                    totalCount,
                    totalPage
                };

                if (list != null)
                {
                    result.Data = aa;

                    result.Msg = "显示成功";
                }
                else
                {
                    result.Msg = "显示失败";
                }
            }
            catch (Exception)
            {

                throw;
            }

            return result;
        }
    }
}
